package com.nowcoder.community.service.impl;

import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService, CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    // @Autowired
    // private LoginTicketMapper loginTicketMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;

    // 注入项目域名
    @Value("${community.path.domain}")
    private String domain;

    // 注入项目路径
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public User findUserById(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        Object userObj = redisTemplate.opsForValue().get(redisKey);
        // 当前user没有被存储在缓存中
        // 去数据库查,再放到缓存里
        if(userObj == null) {
            User user = userMapper.selectById(userId);
            redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
            return user;
        }
        else {
            return (User) userObj;
        }
    }

    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        // 前端传回null
        if(user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if(StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "用户账号不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "用户密码不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "用户邮箱不能为空!");
            return map;
        }

        // 验证账号是否已经被使用
        List<User> u = userMapper.selectByName(user.getUsername());
        if(u != null && !u.isEmpty()) {
            map.put("usernameMsg", "用户账号已经存在!");
            return map;
        }

        // 验证邮箱是否已经存在
        u = userMapper.selectByEmail(user.getEmail());
        if(u != null && !u.isEmpty()) {
            map.put("emailMsg", "用户邮箱已经被注册!");
            return map;
        }

        // 注册用户
        // 取5位的salt
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));

        user.setType(0);
        // 新注册用户处于未激活状态
        user.setStatus(0);
        // 这是激活码
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("https://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));

        user.setCreateTime(new Date());

        // 这一步mybatis会回填用户ID
        // 在配置文件中启用: useGeneratedKeys = true
        userMapper.insertUser(user);

        // 给用户发送激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());

        String url = domain + contextPath + "/activation" + "/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);

        String htmlContent = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "牛客网账号激活邀请", htmlContent);

        return map;
    }

    @Override
    public int activate(int userId, String code) {
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        }
        else if(user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            return ACTIVATION_SUCCESS;
        }
        else {
            return ACTIVATION_FAIL;
        }
    }

    @Override
    public Map<String, Object> login(String username, String password, long expireSeconds) {
        Map<String, Object> msg = new HashMap<>();

        // 空值处理
        if(StringUtils.isBlank(username)) {
            msg.put("usernameMsg", "账号不能为空!");
            return msg;
        }
        if(StringUtils.isBlank(password)) {
            msg.put("passwordMsg", "密码不能为空!");
            return msg;
        }

        // 验证账号
        // 用户名是否存在
        // 用户名和密码是否匹配
        // 用户当前处于什么状态
        List<User> users = userMapper.selectByName(username);
        if(users == null || users.isEmpty()) {
            msg.put("usernameMsg", "该账号不存在!");
            return msg;
        }
        User targetUser = users.get(0);
        if(targetUser.getStatus() == 0) {
            msg.put("usernameMsg", "该账号未激活!");
            return msg;
        }

        // 验证密码
        password = CommunityUtil.md5(password + targetUser.getSalt());
        if(!targetUser.getPassword().equals(password)) {
            msg.put("passwordMsg", "密码不正确!");
            return msg;
        }

        // 生成并插入登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(targetUser.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + 1000 * expireSeconds));

        // loginTicketMapper.insertLoginTicket(loginTicket);
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        // Redis会自动把LoginTicket对象序列化为一个JSON字符串
        redisTemplate.opsForValue().set(redisKey, loginTicket);

        msg.put("ticket", loginTicket.getTicket());
        return msg;
    }

    @Override
    public void logOut(String ticket) {
        // loginTicketMapper.updateStatus(ticket, 1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    @Override
    public LoginTicket findLoginTicket(String ticket) {
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    @Override
    public int updateHeader(int userId, String headerURL) {
        return userMapper.updateHeader(userId, headerURL);
    }

    @Override
    public Map<String, Object> updateUserPassword(User user, String originPassword, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        if(StringUtils.isBlank(originPassword)) {
            map.put("orgPasswordMsg", "原始密码不能为空!");
            return map;
        }
        if(StringUtils.isBlank(newPassword)) {
            map.put("newPasswordMsg", "新密码不能为空!");
            return map;
        }
        // 检查原密码是否正确
        String testPassword = CommunityUtil.md5(originPassword + user.getSalt());
        if(!user.getPassword().equals(testPassword)) {
            map.put("orgPasswordMsg", "原始密码填写不正确!");
            return map;
        }
        // 加一个正则表达式检查的逻辑
        String pattern = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#]).{8,}$";
        Pattern regex = Pattern.compile(pattern);
        Matcher matcher = regex.matcher(newPassword);
        if(!matcher.matches()) {
           map.put("newPasswordMsg", "新密码格式不正确!");
           return map;
        }
        // String newSalt = CommunityUtil.generateUUID().substring(0, 5);
        newPassword = CommunityUtil.md5(newPassword + user.getSalt());
        userMapper.updatePassword(user.getId(), newPassword);
        return map;
    }

    @Override
    public User findUserByName(String username) {
        List<User> list = userMapper.selectByName(username);
        if(list != null && !list.isEmpty()) {
            return list.get(0);
        }
        else {
            return null;
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = findUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 2:
                        return AUTHORITY_MODERATOR;
                    case 1:
                        return AUTHORITY_ADMIN;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }
}
